/**
 * The contents of this file are subject to the license and copyright detailed in the LICENSE and NOTICE files at the root of the source tree and available online at
 * http://www.askosi.org/license.html
 */
package be.destin.skos.core;

import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Christophe Dupriez
 * TODO: check getIndex and setIndex validity for SchemeUsage that is not Count !!!
 */
public class SchemeUsageList extends LinkedList<SchemeUsage> {

	public static final long serialVersionUID = 1;

	Map<String/*Application+Role*/,SchemeUsage > usageMap = new ConcurrentHashMap<String,SchemeUsage>();
	
	public SchemeUsage find(String application, String aRole) {
		if (application == null) return null;
		if (aRole == null) return null;
		return usageMap.get(application+SchemeInterface.fieldSeparator+aRole);
	}

	public boolean put(SchemeUsage aRoleUsage) {
		String application = aRoleUsage.getApplication();
		String aRole = aRoleUsage.getRole();
		SchemeUsage aUse = usageMap.get(application+SchemeInterface.fieldSeparator+aRole);
		if (aUse != null) {
			aUse.setPropagated(aRoleUsage.isPropagated());
			aUse.setSearchURL(aRoleUsage.getSearchURL());
			aUse.setPreviewURL(aRoleUsage.getPreviewURL());
			aUse.setCompleteURL(aRoleUsage.getCompleteURL());
			aUse.setHarvestURL(aRoleUsage.getHarvestURL());
			aUse.setHarvestCondition(aRoleUsage.getHarvestCondition());
			aUse.setHarvestFailure(aRoleUsage.getHarvestFailure());
			aUse.setHarvestCount(aRoleUsage.getHarvestCount());
			aUse.setAtomURL(aRoleUsage.getAtomURL());
			long currCount = aUse.getTotal();
			long newCount = aRoleUsage.getTotal();
			if (currCount != newCount) {
				aUse.setTotal(newCount);
				return true;
			}
			return false;
		} else {
			usageMap.put(application+SchemeInterface.fieldSeparator+aRole,aRoleUsage);
			this.add(aRoleUsage);
			return true;
		}
	}

	public synchronized void index() {
		usageMap = new ConcurrentHashMap<String,SchemeUsage>();
		for (SchemeUsage schemeUsage : this) {
			String application = schemeUsage.getApplication();
			String aRole = schemeUsage.getRole();
			usageMap.put(application+SchemeInterface.fieldSeparator+aRole,schemeUsage);
		}
	}

	/**
	 * @return the knownIndexes for an Application
	 */
	public LinkedList<SchemeUsage> getApplicationUsage(String application) {
		LinkedList<SchemeUsage> result = new LinkedList<SchemeUsage>();
		for (SchemeUsage aUsage : this) {
			if (aUsage.getApplication().equals(application)) {
				result.add(aUsage);
			}
		}
		return result;
	}

	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append(this.size());
		result.append("*SchemeUsage=[");
		for (SchemeUsage aSchemeUsage: this) {
			result.append(aSchemeUsage.toString());
			result.append(';');
		}
		return result.append(']').toString();
	}
}
